package com.ptc.ims.client.util;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

/**
 * TODO message.properties , also see ValidatorCreator
 * @author Gelo
 *
 */
public class Validator
{
	private static final String PRODUCT_NAME_PATTERN = "[A-Za-z0-9]+";	
	private final RegExp PATTERN = RegExp.compile(PRODUCT_NAME_PATTERN);
	
	public List<String> validate(String name, String price)
	{
		List<String> errors = validateProductName(name, null);
		return validatePrice(price, errors);
	}
	
	public List<String> validateProductName(String name, List<String> errors)
	{
		if (errors == null)
		{
			errors = new ArrayList<String>();
		}
		if (isBlank(name))
		{
			errors.add("Product name is required");
		}
		else
		{
			MatchResult matcher = PATTERN.exec(name);
			if (matcher == null)
			{
				errors.add("Product name should have atleast one alphanumeric character");
			}
		}
		return errors;
	}
	
	public List<String> validatePrice(String price, List<String> errors)
	{
		if (errors == null)
		{
			errors = new ArrayList<String>();
		}
		if (isBlank(price))
		{
			errors.add("Product price is required");
		}
		else
		{
			if (!isNumber(price))
			{
				errors.add("Product price should be a number");
			}
			else
			{
				double priceDouble = Double.parseDouble(price);
				if (priceDouble <= 0)
				{
					errors.add("Product price should be greater than 0");
				}
				else if (priceDouble > 300.0)
				{
					errors.add("Product price should be a less than 300");
				}
			}
		}
		
		return errors;
	}
	
	/**
	 * @return true if string is null or empty
	 */
	private boolean isBlank(String testString)
	{
		boolean isBlank = true;
		if (testString != null && testString.trim().length() > 0)
		{
			isBlank = false;
		}
		return isBlank;
	}
	
	private boolean isNumber(String testString)
	{
		boolean isNumber = true;
		
		try
		{
			Double.valueOf(testString);
		}
		catch (NumberFormatException e) 
		{
			isNumber = false;
		}
	
		return isNumber;
	}
}
